package sys
{
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	
	import struct.HashMap;

	/**
	 *数据处理 
	 * @author 张进辉
	 * 
	 */	
	public class CoreModel
	{
		/**数据缓存*/
		private var _data:HashMap;
		
		private var _classMap:Dictionary = new Dictionary;
		
		public function CoreModel()
		{
			
		}
		
		/**
		 *通过xml配置文件注册类 
		 * @param xml: 配置文件包含<regCls name='xx' cls='yy'/> 
		 * 
		 */		
		public function regClass(xml:XML):void
		{
			var xmllist:XMLList = xml.children();
			for each (var xm:XML in xmllist) 
			{
				var name:String = xm.regCls.@name;
				var cls:Class = ApplicationDomain.currentDomain.getDefinition(xm.regCls.@cls) as Class;	
				if(!name || !cls) throw new Error("配置的类名无效");
				
				_classMap[name] = cls;
			}
		}
		
		/**
		 *生成数据文件 
		 * @param data：包含{name:类名，value:kv格式的数据}
		 * 
		 */		
		public function createModel(data:Array):void
		{
			for each (var i:Object in data) 
			{
				saveData(i.name,i.value);
			}
		}
		
		public function getDataFromeId(id:String,clsName:String):Object
		{
			var clsArr:Array = _data.getValue(clsName);
			for each (var i:int in clsArr) 
			{
				
			}
			
			return null;
		}
		
		public function getClsFromName(name:String):Array
		{
			var arr:Array = _data.getValue(name);
			if(arr == null)
			{
				arr = [];
				_data.put(name,arr);
			}
			return arr;
		}
		
		/**
		 *保存数据 
		 * @param name：类名
		 * @param data：类值
		 * 
		 */		
		public function saveData(name:String,data:Object):void
		{
			var arr:Array = getClsFromName(name);
			var cls:Class = _classMap[name];
			if(cls == null) throw new Error("存在未注册的类名"+name);
			
			var instance:Object = new cls();
			for(var key:String in data)
			{
				if(instance.hasOwnProperty(key))
					instance[key] = data[key];
			}
			
			arr.push(instance);
		}
		
	}
}